from sqlite3 import *


class DB(object):
    """Class responsible for administering the database."""
    def __init__ (self):
        """Connect or create the database if not exist."""

        self.conn = connect('data.db')
        self.cursor = self.conn.cursor()

        try: 
            # Create table if not exist
            self.cursor.execute('''CREATE TABLE data (key TEXT, sound TEXT, to_send TEXT, time NUMERIC)''')

        except OperationalError, msg: 
            #print "Error: La tabla ya existe.\n"
            pass

    def add (self, tuple):
        """
        Insert 4-upla in the database.

        tuple is 4-upla (string, string, string)
        """

        self.cursor.execute('INSERT INTO data (key, sound, to_send, time) VALUES (?,?,?,?)', tuple)


    def search (self, key):
        """Looking for a 4-upla from a key in the database."""

        self.cursor.execute('SELECT * FROM data WHERE key =?', key)

        if self.cursor:           # if not empty
            return self.cursor.fetchone()
        


if __name__ == "__main__":
    db = DB()

    # Add some rows
    t = [("a","pepe.wav","a",2),
         ("b","vaca.mp3","3",6),
         ("c","Atom hear mother suite - Pink Floyd :P.mp3","f",521)]

    for some in t:
        db.add(some)

    # search

    tuple = db.search("c")
    print tuple

    # print all rows

    db.cursor.execute('select * from data')

    for row in db.cursor:
        print row
        type(db.cursor)
